package toolkit

import (
	"github.com/go-co-op/gocron"
	"io/ioutil"
	"mgs/global"
	"os"
	"path/filepath"
	"time"
)

func InitScheduler() {
	sysCfg := global.CONFIG.System
	if sysCfg.TempCleanInterval > 0 {
		s := gocron.NewScheduler(time.UTC)
		// 临时文件清理
		_, err := s.Every(sysCfg.TempCleanInterval).Minutes().Do(cleanTemp, sysCfg.TempPath)
		if err != nil {
			panic(err)
		}
		s.StartBlocking()
	}
}

func cleanTemp(tempPath string) {
	files, _ := filePathWalkDir(tempPath)
	addTime := time.Now().Local().Add(time.Minute * time.Duration(-1))
	for _, file := range files {
		fs, err := os.Stat(file)
		if err == nil {
			// 删除三十分钟前的临时文件
			if addTime.After(fs.ModTime()) {
				os.Remove(file)
			}
		}
	}
}

func filePathWalkDir(root string) ([]string, error) {
	var files []string
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
		if path != root {
			if info.IsDir() {
				dir, _ := ioutil.ReadDir(path)
				if len(dir) == 0 {
					// 删除空文件夹
					os.RemoveAll(path)
				}
			} else {
				files = append(files, path)
			}
		}
		return nil
	})
	return files, err
}
